package com.zxzw.scanningin

import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.speech.tts.TextToSpeech
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Toast
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.zxzw.scanningin.http.AppConfig
import com.zxzw.scanningin.http.request
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {
    private lateinit var previousPendingIntent: PendingIntent
    private lateinit var text2Speech: TextToSpeech
    private lateinit var androidId: String
    private val launch = CoroutineScope(Dispatchers.IO)

    private var techLists: Array<out Array<String>>? = null
    private var intentFilters: Array<IntentFilter>? =null

    private lateinit var  nfcAdapter: NfcAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MMKVUtils.init(this)
        AppConfig.baseUrl = MMKVUtils.getString(MMKVUtils.HOME,AppConfig.baseUrl)?:AppConfig.baseUrl
        initTTs()
        getIMei()
        initNFC()
        findViewById<View>(R.id.setting).setOnClickListener {
            setHomeApi()
        }
        UsbKeyboardAutoScan.getInstance().setOnScanListener {
            Log.e("<<<<<<<code2>>",it)
//            text2Speech.speak(it, TextToSpeech.QUEUE_FLUSH,null)
            if (!it.isNullOrEmpty() && it.split("&").isNotEmpty() && it.split("&").size>1){
                Log.e("<<<<<<<大一ing>>","${it.split("&")[0]}>>>>${it.split("&")[1]}")
                signMethod(it.split("&")[0],it.split("&")[1])
            }else{
                Toast.makeText(this,"请扫描正确的二维码",Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun setHomeApi(){
        var current = MMKVUtils.getString(MMKVUtils.HOME, AppConfig.baseUrl)
        XPopup.Builder(this).asInputConfirm("环境配置",current,current) {
            if (AppConfig.baseUrl != it && !it.isNullOrEmpty()){
                AppConfig.baseUrl = it
                MMKVUtils.set(MMKVUtils.HOME,it)
            }
        }.show()
    }

    private fun initTTs(){
        text2Speech = TextToSpeech(this) {
            if (it == TextToSpeech.SUCCESS){
                text2Speech.setPitch(1.0f)
                text2Speech.setSpeechRate(1.0f)
            }
        }
    }

    private fun initNFC(){
        nfcAdapter = NfcAdapter.getDefaultAdapter(this)
        if (null == nfcAdapter){
            Toast.makeText(this,"不支持NFC功能",Toast.LENGTH_LONG).show()
            return
        }

        var tech = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
        var tag = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED)
        var ndff = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        intentFilters = arrayOf(tech,tag,ndff)
        techLists = Uitls.getTechList()
        previousPendingIntent  = PendingIntent.getActivity(this,0,
            Intent(this,javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
    }

    private var isWaitRequest: Boolean = false
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        Log.e("<<<<<<","来来来>>:${intent?.action}")
        if (NfcAdapter.ACTION_TECH_DISCOVERED == intent?.action){
            var parcelableExtra = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent?.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG,Tag::class.java)
            } else {
                intent?.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            }
            var bytesToHex = Uitls.bytesToHex(parcelableExtra?.id)
            Log.e("<<<<<<","来来来>>:$bytesToHex")
            if (!isWaitRequest){
                isWaitRequest = true
                cardSignMethod(bytesToHex)
//                cardSignMethod("847086CB")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (nfcAdapter != null){
            if (nfcAdapter!!.isEnabled){
                nfcAdapter!!.enableForegroundDispatch(this,previousPendingIntent,intentFilters,techLists)
            }else{
                startActivity(Intent(Settings.ACTION_NFC_SETTINGS))
            }
        }
    }

    override fun onPause() {
        super.onPause()
        try {
            dismissPop()
            nfcAdapter?.disableForegroundDispatch(this)
        }catch (e: Exception){
            Log.e("<<<<<","没看懂")
        }
    }

    private fun getIMei(){
//        var systemService = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
//        var deviceId = systemService.deviceId
        androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
        Log.e("<<<TAG>>>", "getIMei: $androidId")
    }
    private var popShow: BasePopupView? = null

    private fun signMethod(id:String,time:String){
        launch.launch {
            request {
                scanSignApi(id,androidId,time)
            }.collect(){
                Log.e("<<<<<","${it.result}>>>>${it.e?.message}")
                var message = it.result?.message
                text2Speech.speak(if (message=="success") "扫码成功" else message, TextToSpeech.QUEUE_FLUSH,null)
                withContext(Dispatchers.Main){
                    dismissPop()
                    popShow = if (it.result?.success == true && message=="success"){
                        XPopup.Builder(this@MainActivity).asCustom(PayResultPop(this@MainActivity,1))
                    }else{
                        XPopup.Builder(this@MainActivity).asCustom(PayResultPop(this@MainActivity,2))
                    }
                    popShow?.show()
                }
            }
        }
    }

    private fun cardSignMethod(num :String){
        launch.launch {
            request {
                cardSignApi(num,androidId)
            }.collect(){
                isWaitRequest = false
                withContext(Dispatchers.Main){
                    dismissPop()
                    if (it.result == null){
                        text2Speech.speak("签到失败" , TextToSpeech.QUEUE_FLUSH,null)
                        popShow = XPopup.Builder(this@MainActivity).asCustom(PayResultPop(this@MainActivity,2))
                    }else{
                        it.result?.apply {
                            text2Speech.speak(if (message=="success") "签到成功" else message, TextToSpeech.QUEUE_FLUSH,null)
                            popShow = if (success && message=="success"){
                                XPopup.Builder(this@MainActivity).asCustom(PayResultPop(this@MainActivity,1))
                            }else{
                                XPopup.Builder(this@MainActivity).asCustom(PayResultPop(this@MainActivity,2))
                            }
                        }
                    }
                    popShow?.show()
                }
            }
        }
    }

    private fun dismissPop(){
        popShow?.apply {
            if (isShow) dismiss()
            popShow = null
        }
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        Log.e("<<<<<<卧槽","${event?.keyCode}")
//        Log.e("<<<<<deviceId<","${event?.deviceId}")
        //解析扫码枪事件
        event?.let {
            if (UsbKeyboardAutoScan.getInstance().isIntercept && it.keyCode != KeyEvent.KEYCODE_BACK){
                UsbKeyboardAutoScan.getInstance().analysisKeyEvent(event)
                return true
            }

        }

        return super.dispatchKeyEvent(event)
    }


}